package org.example.controller;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.example.common.dto.HotelDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class ESController {

    @Autowired
    private RestHighLevelClient client;
    @RequestMapping(value = "/color")
    public List<HotelDto> color() throws IOException {
        SearchRequest request = new SearchRequest("hotel");

        request.source().query(QueryBuilders.matchQuery("city","北京"));
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        return print1(response);
    }

    private List<HotelDto> print1(SearchResponse response)
    {
        SearchHits searchHits = response.getHits();
        SearchHit[] hits = searchHits.getHits();

        long value = searchHits.getTotalHits().value;
        List<HotelDto> hotelDtos = new ArrayList<>();
        for (SearchHit hit : hits) {
            String sourceAsString = hit.getSourceAsString();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
//            for (Map.Entry<String, HighlightField> stringHighlightFieldEntry : highlightFields.entrySet()) {
//                HighlightField value1 = stringHighlightFieldEntry.getValue();
//                System.out.println(value1);
//                String key = stringHighlightFieldEntry.getKey();
//                System.out.println(key);
//            }

            HotelDto hotelDto = JSON.parseObject(sourceAsString, HotelDto.class);
            //
            hotelDtos.add(hotelDto);
            HighlightField name = highlightFields.get("name");
            if (name != null)
            {
                Text fragment = name.getFragments()[0];
                String s = fragment.string();
                hotelDto.setName(s);
            }
        }

        return hotelDtos;
    }
}
